import axios from 'axios';
import merge from 'lodash.merge';
import NProgress from 'nprogress';
import {Message, MessageBox} from 'element-ui';
import {Axios, Store, Router, Objects} from '@v2coding/ui';
import routes from './config/router/routes';
import state from './config/store/state';
import mutations from './config/store/mutations';
import getters from './config/store/getters';

const logout = () => {
  const store = Store.getStore();
  const router = Router.getRouter();
  showError('您的账号因在其它地方登录或长时间无操作而失效,请重新登录!');
  store.commit('authorization', '');
  // localStorage.removeItem('MICRO_TOKEN');
  router.replace({path: '/login'});
};

let messageTimer;
const showError = (msg) => {
  clearTimeout(messageTimer);
  messageTimer = setTimeout(() => {
    Message.error(msg);
  }, 200);
};

const AllowCodeList = [
  'SUCCESS',
];

Axios.addInterceptor(Axios.Interceptor.RequestSuccess, (request) => {
  // const token = localStorage.getItem('MICRO_TOKEN');
  const token = Store.getStore().state.authorization
  if (token) {
    request.headers['authorization'] = token;
  }
  request.headers = merge({
    'Accept': 'application/json, */*',
    'X-Requested-With': 'XMLHttpRequest',
    'V2Coding-Client-Device': 'Desktop',
  }, request.headers || {});
  return request;
});

Axios.addInterceptor(Axios.Interceptor.ResponseSuccess, (response) => {
  if (response.data.code === 501) {
    let msg = response.data.message
    showError(msg)
  } else if (response.data.code === 401) {
    logout();
    const msg = '您的账号因在其它地方登录或长时间无操作而失效,请重新登录!'
    showError(msg)
    return {success: false, code: -1};
  }
  return response.data;
});

Axios.addInterceptor(Axios.Interceptor.ResponseError, (error) => {
  console.log('ResponseError', error);
  const {response = {}} = error || {};
  let msg = '网络出现故障,请稍后再试';
  switch (response.status) {
    case 401:
    case 403:
      logout();
      return {success: false, code: -1};
  }
  if (Math.floor(response.status / 100) === 5) {
    msg = '服务出现故障,请稍后再试';
  }
  if (error?.code === 'ECONNABORTED' && (error?.message || '').indexOf('timeout') !== -1) {
    msg = '网络请求超时，请稍后再试';
  }
  const {code, message} = response.data || {};
  if (!axios.isCancel(error) && !AllowCodeList.includes(code)) {
    msg = message || msg;
    showError(msg);
  }
  if (Objects.hasProp(response.data, 'code', 'success')) {
    return response.data;
  }
  return Promise.reject(error);
});

Router.addInterceptor(Router.Interceptor.Before, (to) => {
  try {
    MessageBox.close();
  } catch (ignore) {
    // ignore
  }
  NProgress.start();
});

Router.addInterceptor(Router.Interceptor.After, (to) => {
  NProgress.done();
  const store = Store.getStore();
  if (to.name === '登录') {
    store.commit('menus'); // 清空菜单
  }
});

export default {
  router: {
    // 正式环境需 nginx 配置支持(try_files $uri $uri/ /index.html;)
    mode: 'history',
    routes: routes,
    base: '/',
  },
  store: {
    persist: {
      key: 'v2coding-show-admin',
      blackList: ['permissions', 'menus'],
    },
    getters,
    state,
    mutations,
  },
};
